package yc.bluetooth.xfvoicerecognize;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.os.LocaleList;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import yc.bluetooth.xfvoicerecognize.permission.PermissionListener;
import yc.bluetooth.xfvoicerecognize.permission.PermissionRequest;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "XFVoiceRecognize";

    //动态申请的权限
    protected String[] requestPermissionArray = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
            };
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    protected List<String> deniedPermissionList = new ArrayList<>();

    //语言环境
    private Locale locale;
    private String language;
    //讯飞语音识别对象
    private SpeechRecognizer speechRecognizer;

    private Button btStartRecognize;
    private Button btStopRecognize;
    private TextView tvRecognizeResult;
    private TextView tvRecognizeState;
    //是否正在识别监听
    private boolean isRecognizing = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initListener();

        //初始化语音识别对象
        initVoiceRecognize();

        //初始化权限
        initPermissions();
    }

    private void initView() {
        btStartRecognize = findViewById(R.id.bt_start_recognize);
        btStopRecognize = findViewById(R.id.bt_stop_recognize);
        tvRecognizeResult = findViewById(R.id.tv_recognize_result);
        tvRecognizeState = findViewById(R.id.tv_recognize_state);
    }

    private void initListener(){
        btStartRecognize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isRecognizing){
                    if(speechRecognizer != null){
                        speechRecognizer.startListening(recognizerListener);
                        tvRecognizeState.setText("正在识别监听...");
                        isRecognizing = true;
                    }
                }
            }
        });

        btStopRecognize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isRecognizing){
                    if(speechRecognizer != null){
                        speechRecognizer.stopListening();
                        tvRecognizeState.setText("结束监听");
                    }
                }
            }
        });
    }

    /**
     * 初始化语音识别对象
     */
    private void initVoiceRecognize() {
        //获取系统默认语言
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = LocaleList.getDefault().get(0);
        } else {
            locale = Locale.getDefault();
        }
        language = locale.getLanguage() + "-" + locale.getCountry();
        Log.d(TAG, "系统默认language:"+language);


        // 初始化识别无UI识别对象
        //使用SpeechRecognizer对象，可根据回调消息自定义界面；
        speechRecognizer = SpeechRecognizer.createRecognizer(MainActivity.this, initListener);
        if(speechRecognizer != null) {
            //设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
            speechRecognizer.setParameter(SpeechConstant.RESULT_TYPE, "plain");
            // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
            //取值范围{1000～10000}
            speechRecognizer.setParameter(SpeechConstant.VAD_BOS, "4000");
            //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
            //自动停止录音，范围{0~10000}
            speechRecognizer.setParameter(SpeechConstant.VAD_EOS, "1000");
            //设置语音输入语言，zh_cn为简体中文,en_us为美式英文
            if (language.equalsIgnoreCase("zh-CN")) {
                // 设置语言
                speechRecognizer.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            } else {
                // 设置语言
                speechRecognizer.setParameter(SpeechConstant.LANGUAGE, "en_us");
            }

            Log.d(TAG, "语音识别对象完成初始化");
        }else{
            Log.d(TAG, "语音识别对象 == null");
        }
    }

    //初始化单例对象时，通过此回调接口，获取初始化状态。
    private InitListener initListener = new InitListener() {
        @Override
        public void onInit(int i) {
            Log.d(TAG, "SpeechRecognizer initListener() code = " + i);
            if (i != ErrorCode.SUCCESS) {
                Log.e(TAG, "语音识别初始化失败，错误码：" + i);
            }else{
                Log.w(TAG, "语音识别初始化成功，错误码：" + i);
            }
        }
    };

    //初始化识别监听器
    private RecognizerListener recognizerListener = new RecognizerListener() {
        @Override
        public void onVolumeChanged(int i, byte[] bytes) { //音量变化
        }

        @Override
        public void onBeginOfSpeech() {   //开始说话
        }

        @Override
        public void onEndOfSpeech() {  //结束说话
            //继续识别，并设置监听器
            speechRecognizer.startListening(recognizerListener);
        }

        @Override
        public void onResult(RecognizerResult recognizerResult, boolean b) { //返回结果 返回的结果可能为null，请增加判断处理。
            if(recognizerResult == null){
                Log.d(TAG, "识别出来 onResult:" + b + "  recognizerResult == null");
            }else {
                Log.d(TAG, "识别出来 onResult:" + b + "    content:" + recognizerResult.getResultString());
                tvRecognizeResult.setText(recognizerResult.getResultString());
            }
        }

        @Override
        public void onError(SpeechError speechError) {  //错误回调
            if(isRecognizing) {
                Log.e(TAG, "语音识别出错 onError()");
            }
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {  //扩展接口
        }
    };

    /**
     * 初始化权限
     */
    private void initPermissions() {
        //Android 6.0以上动态申请权限
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            final PermissionRequest permissionRequest = new PermissionRequest();
            permissionRequest.requestRuntimePermission(MainActivity.this, requestPermissionArray, new PermissionListener() {
                @Override
                public void onGranted() {
                    Log.d(TAG,"所有权限已被授予");
                }

                //用户勾选“不再提醒”拒绝权限后，关闭程序再打开程序只进入该方法！
                @Override
                public void onDenied(List<String> deniedPermissions) {
                    deniedPermissionList = deniedPermissions;
                    for (String deniedPermission : deniedPermissions) {
                        Log.e(TAG,"被拒绝权限：" + deniedPermission);
                    }
                }
            });
        }
    }
}
